/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pig.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.admin.api.entity.SysRoleDept;
import com.pig4cloud.pig.admin.mapper.SysRoleDeptMapper;
import com.pig4cloud.pig.admin.service.SysRoleDeptService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色部门表
 *
 * @author dych
 * @date 2021-10-05 20:47:58
 */
@Service
public class SysRoleDeptServiceImpl extends ServiceImpl<SysRoleDeptMapper, SysRoleDept> implements SysRoleDeptService {

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdate(Integer roleId, List<Integer> deptIdList) {
		//先删除角色与部门关系
		deleteBatch(new Integer[]{roleId});

		if(deptIdList.size() == 0){
			return ;
		}

		//保存角色与菜单关系
		for(Integer deptId : deptIdList){
			SysRoleDept sysRoleDept = new SysRoleDept();
			sysRoleDept.setDeptId(deptId);
			sysRoleDept.setRoleId(roleId);
			this.save(sysRoleDept);
		}
	}

	@Override
	public List<Integer> queryDeptIdList(Integer[] roleIds) {
		return baseMapper.queryDeptIdList(roleIds);
	}

	@Override
	public int deleteBatch(Integer[] roleIds){
		return baseMapper.deleteBatch(roleIds);
	}

	@Override
	@Transactional
	public void saveRoleDept(Integer deptId, List<Integer> roleIdList) {
		//先删除部门关联角色集合
		LambdaQueryWrapper<SysRoleDept> sysRoleDeptLambdaQueryWrapper = new LambdaQueryWrapper<>();
		sysRoleDeptLambdaQueryWrapper.eq(SysRoleDept::getDeptId, deptId);
		this.baseMapper.delete(sysRoleDeptLambdaQueryWrapper);
		//保存角色部门关联关系
		if (CollectionUtil.isNotEmpty(roleIdList)) {
			for (Integer roleId : roleIdList) {
				SysRoleDept sysRoleDept = new SysRoleDept();
				sysRoleDept.setDeptId(deptId);
				sysRoleDept.setRoleId(roleId);
				this.baseMapper.insert(sysRoleDept);
			}
		}
	}
}
